package com.example.mylibrary.network

import com.google.gson.GsonBuilder
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.simplexml.SimpleXmlConverterFactory
import java.lang.reflect.Type

class MultipleConverterFactory : Converter.Factory() {
    private var jsonFactory: Converter.Factory
    private var xmlFactory: Converter.Factory

    init {
        val gson = GsonBuilder()
            .serializeNulls()
            .create()
        jsonFactory = GsonConverterFactory.create(gson)


        xmlFactory = SimpleXmlConverterFactory.createNonStrict()
    }

    companion object {
        fun create() = MultipleConverterFactory()
    }

    override fun responseBodyConverter(
        type: Type,
        annotations: Array<Annotation>,
        retrofit: Retrofit
    ): Converter<ResponseBody, *>? {
        for (annotation in annotations) {
            if (annotation is ResponseConverter) {
                return when (annotation.format) {
                    ConverterFormat.JSON -> {
                        jsonFactory.responseBodyConverter(type, annotations, retrofit)
                    }
                    ConverterFormat.XML -> {
                        xmlFactory.responseBodyConverter(type, annotations, retrofit)
                    }
                }
            }
        }
        return jsonFactory.responseBodyConverter(type, annotations, retrofit)
    }

    override fun requestBodyConverter(
        type: Type,
        parameterAnnotations: Array<Annotation>,
        methodAnnotations: Array<Annotation>,
        retrofit: Retrofit
    ): Converter<*, RequestBody>? {
        for (annotation in methodAnnotations) {
            if (annotation is RequestConverter) {
                return when (annotation.format) {
                    ConverterFormat.JSON -> {
                        jsonFactory.requestBodyConverter(
                            type,
                            parameterAnnotations,
                            methodAnnotations,
                            retrofit
                        )
                    }
                    ConverterFormat.XML -> {
                        xmlFactory.requestBodyConverter(
                            type,
                            parameterAnnotations,
                            methodAnnotations,
                            retrofit
                        )
                    }
                }
            }
        }
        return jsonFactory.requestBodyConverter(
            type,
            parameterAnnotations,
            methodAnnotations,
            retrofit
        )
    }
}